<?php

/**
 *		//核心函数//
 *		//这是一份试验品，由大街编写（zhongmingzi@gmail.com）
 *		//本程序默认环境：Zend Optimizer Yes / 3.3.3
 *		//		Apache/2.0.63 (Win32) PHP/5.2.12
 *		//		MySQL 支持 Yes / client lib version 5.0.89
 *		//		GD library Yes / bundled (2.0.34 compatible)
 *		//		eAccelerator/Memcache/xcache Yes
 *		//		cURL support enabled
 *		//时间：2010 09 21 03:04:23//
 */

if(!defined('IN')) {
	exit('Access Denied');
}

define('CORE_FUNCTION', true);

/*
	数据库，入库相关相关
*/

function dimplode($array, $type = 1) {
	if(!is_array($array)) $array = array($array);
	$c = $type == 0 ? '' : ',';
	foreach($array as $v) {
		$str .= $c.' '.$v;
		$c = ',';
	}
	return $str;
}

//这里只针对UTF8的情况
function removebom($str) {
	if(ord($str{0}) == 239 && ord($str{1}) == 187 && ord($str{2}) == 191 && ord($str{3}) == 239 && ord($str{4}) == 187 && ord($str{5}) == 191) {
		$len = strlen($str) + 6;
		for($i = 6; $i < $len; $i ++) {
			$s .= $str{$i};
		}
		$str = $s;
	}
	return $str;
}

/* 如果count=0，则查询，如果count有数，则不查询数据库 */
function prepage($page, $limit, $count = 0, $sql = '') {

	$limit = abs(intval($limit));
	if($count == 0 && !empty($sql)) {
		$sqls = preg_replace(array('/SELECT.*?FROM /As', '/ORDER BY .*/'), array('SELECT COUNT(*) FROM ', ''), $sql);
		$count = DB::result_first($sqls);
	}
	
	$ptotal = ceil($count / $limit);
	$page = $page > $ptotal ? $ptotal : $page ;

	$offset = (empty($page)||$page == 1) ? 0 : (($page - 1) * $limit);
	
	$return = array(
		'offset' => $offset,
		'limit' => $limit,
		'total' => (int)$count,
		'ptotal' => (int)$ptotal
	);
	return $return;
}

function isemail($email) {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

function formhash($specialadd = '') {
	global $_G;
	$hashadd = defined('IN_ADMINCP') ? 'Only For Admin!' : '';
	return substr(md5(substr($_G['timestamp'], 0, -7).$_G['username'].$_G['uid'].$_G['authkey'].$hashadd.$specialadd), 8, 8);
}

function strexists($string, $find) {
	return !(strpos($string, $find) === FALSE);
}

/*
	文件操作，读取，上传相关
*/

function fileext($filename) {
	return addslashes(trim(substr(strrchr($filename, '.'), 1, 10)));
}

function dmkdir($dir, $mode = 0777, $makeindex = true) {
	if(!is_dir($dir)) {
		dmkdir(dirname($dir));
		@mkdir($dir, $mode);
		if(!empty($makeindex)) {
			@touch($dir.'/index.html'); @chmod($dir.'/index.html', 0777);
		}
	}
	return true;
}

function libfile($libname, $folder = '', $app = '') {
	if($app != '') $appath = "./app/".$app.'/';
	else $appath = './framework/';
	$libpath = ROOT.$appath.$folder;
	if(strstr($libname, '/')) {
		list($pre, $name) = explode('/', $libname);
		return realpath("{$libpath}/{$pre}/{$pre}_{$name}.php");
	} else {
		return realpath("{$libpath}/{$libname}.php");
	}
}

function sizecount($size) {
	if($size >= 1073741824) {
		$size = round($size / 1073741824 * 100) / 100 . ' GB';
	} elseif($size >= 1048576) {
		$size = round($size / 1048576 * 100) / 100 . ' MB';
	} elseif($size >= 1024) {
		$size = round($size / 1024 * 100) / 100 . ' KB';
	} else {
		$size = $size . ' Bytes';
	}
	return $size;
}

function return_bytes($val) {
	$val = trim($val);
	$last = strtolower($val{strlen($val)-1});
	switch($last) {
		case 'g': $val *= 1024;
		case 'm': $val *= 1024;
		case 'k': $val *= 1024;
	}
	return $val;
}

function ftpcmd($cmd, $arg1 = '') {
	static $ftp;
	$ftpon = getglobal('setting/ftp/on');
	if(!$ftpon) {
		return $cmd == 'error' ? -101 : 0;
	} elseif($ftp == null) {
		require_once libfile('class/ftp');
		$ftp = & ftp::instance();
	}
	if(!$ftp->enabled) {
		return 0;
	} elseif($ftp->enabled && !$ftp->connectid) {
		$ftp->connect();
	}
	switch ($cmd) {
		case 'upload' : return $ftp->upload(getglobal('setting/attachdir').'/'.$arg1, $arg1); break;
		case 'delete' : return $ftp->ftp_delete($arg1); break;
		case 'close'  : return $ftp->ftp_close(); break;
		case 'error'  : return $ftp->error(); break;
		case 'object' : return $ftp; break;
		default       : return false;
	}

}

function dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
	require_once libfile('function/filesock');
	return _dfsockopen($url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block);
}

function writelog($file, $log) {
	global $_G;
	$yearmonth = dgmdate(TIMESTAMP, 'Ym', $_G['setting']['timeoffset']);
	$logdir = ROOT.'./data/log/';
	$logfile = $logdir.$yearmonth.'_'.$file.'.php';
	if(@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while($entry = readdir($dir)) {
			if(strexists($entry, $yearmonth.'_'.$file)) {
				$id = intval(substr($entry, $length + 8, -4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);

		$logfilebak = $logdir.$yearmonth.'_'.$file.'_'.($maxid + 1).'.php';
		@rename($logfile, $logfilebak);
	}
	if($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		$log = is_array($log) ? $log : array($log);
		foreach($log as $key => $tmp) {
			if(is_array($tmp)) {
				foreach($tmp as $k => $v) {
					if(is_array($v)) {
						$st = 'array( ';
						foreach($v as $mk => $mv) {
							$st .= str_replace(array('<?', '?>'), '', $mk)." => ".str_replace(array('<?', '?>'), '', $mv).", ";
						}
						$st .= ' )';
						$str .= str_replace(array('<?', '?>'), '', $k)." => ".str_replace(array('<?', '?>'), '', $st).", \n";
						$st = '';
					} else {
						$str .= str_replace(array('<?', '?>'), '', $k)." => ".str_replace(array('<?', '?>'), '', $v).", ";
					}
				}
				fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $key)." =array( {$str})\n");
				$str = '';
			} else {
				fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>'), '', $key)." => ".str_replace(array('<?', '?>'), '', $tmp)."\n");
			}
		}
		fclose($fp);
	}
}

/*
	用户相关
*/

function ipconvert($ip, $nocn = false) {
	include_once libfile("class/ipconvert");
	$ip = new ip($ip);
	return $ip->get($nocn);
}

function getuserbyuid($uid) {
	static $users = array();
	if(empty($users[$uid])) {
		$users[$uid] = DB::fetch_first("SELECT m.*, ms.* FROM ".DB::table('u_members')." m 
			LEFT JOIN ".DB::table('u_members_pro')." ms USING(uid) 
			WHERE m.uid='$uid'");
	}
	return $users[$uid];
}


function updatesession($force = false) {
	global $_G;
	static $updated = false;
	if(!$updated) {
		$lab = & core::instance();
		$oltimespan = $_G['setting']['oltimespan'];
		$lastolupdate = $lab->session->var['lastolupdate'];
		//这段代码用来更新在线累计时间,大约是每10分钟添加一次
		if($_G['uid'] && $oltimespan && TIMESTAMP - ($lastolupdate ? $lastolupdate : $_G['member']['lastactivity']) > $oltimespan * 60) {
			DB::query("UPDATE ".DB::table('u_members')."
				SET oltime=oltime+'$oltimespan', lastactivity=".TIMESTAMP."
				WHERE uid='{$_G['uid']}'");
			$lab->session->set('lastolupdate', TIMESTAMP);
		}
		//这里用来增加session里的用户隐身与否，或者其他需要储存的信息
		foreach($lab->session->var as $k => $v) {
			if(isset($_G['member'][$k]) && $k != 'lastactivity') {
				$lab->session->set($k, $_G['member'][$k]);
			}
		}

		foreach($_G['action'] as $k => $v) {
			$lab->session->set($k, $v);
		}
		//把上面添加的所有session的信息进行更新到数据库
		$lab->session->update();

		$updated = true;
		//这里对DB中的count的lastvisit和lastactivity进行更新,这里一般考虑的是没有经过注册或者登陆而直接通过cookie登陆的人
		//在这里进行着更新
		if($_G['uid'] && TIMESTAMP - $_G['member']['lastactivity'] > 21600) {//6小时
			$ipconv = ipconvert($_G['ip']);
			$city = $ipconv['country_code'] == 'CN' ? $ipconv['cncity'] : $ipconv['city'];
			$code = $ipconv['country_code'];
			DB::update('u_members', array('lastip' => $_G['ip'], 'lastactivity' => TIMESTAMP, 'lastvisit' => TIMESTAMP), "uid='$_G[uid]'", 1);
			DB::update('u_members_pro', array('city' => $city, 'code' => $code), "uid='$_G[uid]'", 1);
		}
	}
	return $updated;
}

function avatarshow($uid = null, $size = "small", $rehtml = false, $username = '') {
	global $_G;
	static $avatar;
	if((isset($uid) && $avatar[$uid]) || (!isset($uid) && ($uid = $_G['uid']) && $avatar[$uid])) return $avatar[$uid];
	if($uid == null || $uid == $_G['uid']) {
		$siteid = $_G['uid'];
		$showname = $_G['username'];
		$return = empty($_G['member']['avatar']) ? 
			($size == 'small' ? URL."/static/image/common/default.s.jpg" : URL."/static/image/common/default.jpg") 
			: ($size == 'small' ? URL.'/data/'.dirname($_G['member']['avatar']).'/s/'.basename($_G['member']['avatar'].'.jpg') : URL.'/data/'.$_G['member']['avatar']);
	} else {
		$query = DB::fetch_first("SELECT avatar, uid, username FROM ".DB::t('u_members')." WHERE uid = '$uid'");
		$siteid = $query['uid'];
		$showname = $query['username'];
		$return = empty($query['avatar']) ? 
			($size == 'small' ? URL."/static/image/common/default.s.jpg" : URL."/static/image/common/default.jpg") 
			: ($size == 'small' ? URL.'/data/'.dirname($query['avatar']).'/s/'.basename($query['avatar'].'.jpg') : URL.'/data/'.$query['avatar']);
	}

	$showname = $username == '' ? $showname : $username;
	$htmlavatar = "<a href=\"".URL."/$siteid \"><img src=\"$return\" alt=\"$showname\" title=\"$showname\"/></a>";
	$return = $rehtml == false ? $return : $htmlavatar;
	return $return;
}

/*
	全局相关
*/

function is_parity($num) {
	return $num % 2 == 0 ? 0 : 1;
}

function daddslashes($string, $force = 1) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			unset($string[$key]);
			$string[addslashes($key)] = daddslashes($val, $force);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

function setglobal($key , $value, $group = null) {
	global $_G;
	$k = explode('/', $group === null ? $key : $group.'/'.$key);
	switch (count($k)) {
		case 1: $_G[$k[0]] = $value; break;
		case 2: $_G[$k[0]][$k[1]] = $value; break;
		case 3: $_G[$k[0]][$k[1]][$k[2]] = $value; break;
		case 4: $_G[$k[0]][$k[1]][$k[2]][$k[3]] = $value; break;
		case 5: $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] =$value; break;
	}
	return true;
}

function getglobal($key, $group = null) {
	global $_G;
	$k = explode('/', $group === null ? $key : $group.'/'.$key);
	switch (count($k)) {
		case 1: return isset($_G[$k[0]]) ? $_G[$k[0]] : null; break;
		case 2: return isset($_G[$k[0]][$k[1]]) ? $_G[$k[0]][$k[1]] : null; break;
		case 3: return isset($_G[$k[0]][$k[1]][$k[2]]) ? $_G[$k[0]][$k[1]][$k[2]] : null; break;
		case 4: return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]] : null; break;
		case 5: return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] : null; break;
	}
	return null;
}

function getgpc($k, $type='GP') {
	$type = strtoupper($type);
	switch($type) {
		case 'G': $var = &$_GET; break;
		case 'P': $var = &$_POST; break;
		case 'C': $var = &$_COOKIE; break;
		default:
			if(isset($_GET[$k])) {
				$var = &$_GET;
			} else {
				$var = &$_POST;
			}
			break;
	}
	return isset($var[$k]) ? $var[$k] : NULL;
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key = md5($key != '' ? $key : getglobal('authkey'));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}

function system_error($message, $show = true, $save = true, $halt = true) {
	require_once libfile('class/error');
	error::system_error($message, $show, $save, $halt);
}

function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {

	global $_G;

	$config = $_G['config']['cookie'];

	$_G['cookie'][$var] = $value;
	$var = ($prefix ? $config['cookiepre'] : '').$var;
	$_COOKIE[$var] = $var;

	if($value == '' || $life < 0) {
		$value = '';
		$life = -1;
	}

	$life = $life > 0 ? getglobal('timestamp') + $life : ($life < 0 ? getglobal('timestamp') - 31536000 : 0);
	$path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'].'; HttpOnly' : $config['cookiepath'];

	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if(PHP_VERSION < '5.2.0') {
		setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);
	} else {
		setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);
	}
}

function getcookie($key) {
	global $_G;
	return isset($_G['cookie'][$key]) ? $_G['cookie'][$key] : '';
}

/* 为防止出错，page统一使用?page=或者&page=的形式 */
function page($total, $page = 1, $page_rule, $securl = SECURL, $form_name = 'page') {
	$patterns = array ("/^\/\?page=\d*\&?(.*)/", "/(.+)&page=\d*$/", "/(.+)&page=\d*\&(.+)/");
	$replace = array ('/?\\1', '\\1', '\\1&\\2');
	$securl = preg_replace($patterns, $replace, $securl);
	$url = $securl.$page_rule;
	$page = $page > $total ? $total:$page;
	$p1 = $page + 1;
	$p2 = $page + 2;
	$pa1 = $page - 1;
	$pa2 = $page - 2;
	$out = $total <= 1 ? "" : "<div class=\"page\">";
	if(!empty($total)&&$total > 1&&$page >= 1) $out .= "<a href=\"".URL.$url.$pa1."\" class=\"pagepre\">&laquo;</a>";
	if($page > 3&&!empty($total)&&$total > 1) $out .= "<a href=\"".URL.$url."1\">1</a>";
	if($page - 3 > 0) $out .= "<span class=\"dot\">&hellip;</span>";
	if($page - 2 > 0) $out .= "<a href=\"".URL.$url.$pa2."\">".$pa2."</a>";
	if($page - 1 > 0) $out .= "<a href=\"".URL.$url.$pa1."\">".$pa1."</a>";
	if(!empty($total)&&$total > 1) $out .= "<span class=\"current\">".$page."</span>";
	if($page + 1 < $total && $total > 1) $out .= "<a href=\"".URL.$url.$p1."\">".$p1."</a>";
	if($page + 2 < $total ) $out .= "<a href=\"".URL.$url.$p2."\">".$p2."</a>";
	if($page + 3 < $total + 1) $out .= "<span class=\"dot\">&hellip;</span>";
	if(!empty($total)&&$total > 1&&$page != $total) $out .= "<a href=\"".URL.$url."$total \">$total</a>";
	if(!empty($total)&&$total > 1&&$page != $total) $out .= "<a href=\"".URL.$url."$p1 \" class=\"pageend\">&#187;</a>";
	if(!empty($total)&&$total > 1&&$page == $total) $out .= "<a href=\"".URL.$url."$total \" class=\"pageend\">&#187;</a>";
	if(!empty($total)&&$total > 1) {
		$out .= "<form method=\"post\" class=\"inline\">";
		$out .= "<input id=\"page_submit\" type=\"submit\" class=\"subbox\" value=\"Turn\">
				 <input id=\"page\" type=\"text\" value=\"".$page."\" name=\"$form_name\">";
		$out .= "</form>";
	}
	$out .= $total <= 1 ? "" : "</div>";
	return $out;
}

function dgmdate($timestamp, $format = 'dt', $timeoffset = '9999', $uformat = '') {//timestamp统一为格林时间戳，第二个为控制人性化时间，天或者时间的参数，第三个参数是时差，第四个控制人性化设置时的时间格式
	global $_G;
	static $dformat, $tformat, $dtformat, $offset;
	if($dformat === null) {
		$dformat = 'Y-m-d';
		$tformat = 'H:i';
		$dtformat = $dformat.' '.$tformat;
		$offset = getglobal('member/timeoffset');//这里是会员的时区设置
	}
	$timeoffset = $timeoffset == 9999 ? (empty($offset) || $offset == 9999 ? 8 : $offset) : $timeoffset;
	$timestamp += $timeoffset * 3600;
	$format = empty($format) || $format == 'dt' ? $dtformat : ($format == 'd' ? $dformat : ($format == 't' ? $tformat : $format));
	if($format == 'u') {
		$todaytimestamp = TIMESTAMP - (TIMESTAMP + $timeoffset * 3600) % 86400 + $timeoffset * 3600;
		$s = gmdate(!$uformat ? $dtformat : $uformat, $timestamp);
		$time = TIMESTAMP + $timeoffset * 3600 - $timestamp;
		if($timestamp >= $todaytimestamp) {
			if($time > 3600) {
				return '<span title="'.$s.'">'.intval($time / 3600).'&nbsp;小时前</span>';
			} elseif($time > 1800) {
				return '<span title="'.$s.'">半小时前</span>';
			} elseif($time > 60) {
				return '<span title="'.$s.'">'.intval($time / 60).'&nbsp;分钟前</span>';
			} elseif($time > 0) {
				return '<span title="'.$s.'">'.$time.'&nbsp;秒前</span>';
			} elseif($time == 0) {
				return '<span title="'.$s.'">刚刚</span>';
			} else {
				return $s;
			}
		} elseif(($days = intval(($todaytimestamp - $timestamp) / 86400)) >= 0 && $days < 7) {
			if($days == 0) {
				return '<span title="'.$s.'">昨天&nbsp;'.gmdate($tformat, $timestamp).'</span>';
			} elseif($days == 1) {
				return '<span title="'.$s.'">前天&nbsp;'.gmdate($tformat, $timestamp).'</span>';
			} else {
				return '<span title="'.$s.'">'.($days + 1).'&nbsp;天前</span>';
			}
		} else {
			return $s;
		}
	} else {
		return gmdate($format, $timestamp);
	}
}

function random($length, $numeric = 0) {
	$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}


function template($name, $renew = 1, $styleid = '', $appid = CURMODULE) {
	global $_G;
	
	include_once libfile('class/template');
	static $tp;
	if(empty($tp)) {
		$tp = new template();
		$tp->templates_dir = ROOT.'./app/'.$appid.'/template';
		$tp->templates_cache = ROOT.'./data/template/'.$appid;
		
		$tp->templates_auto = 1;//自动更新模板
		$tp->templates_new = $renew;//设置当次是否更新
		$tp->templates_time = 360;//设置更新模板缓存时间，分钟计时
		$tp->templates_space = true;//清除无意义字符
		$tp->templates_js = false;//var_dump($renew);exit();
		
		$tp->templates_php = NULL;//在每个页面都会载入，头部和尾部出现的东东
		$tp->templates_postfix = '.html';//自制模板的后缀
	}
	return $tp->display($name);
}

function ipbanned($onlineip) {
	global $_G;

	//loadcache('ipbanned');
	if(empty($_G['cache']['ipbanned'])) {
		return FALSE;
	} else {
		if($_G['cache']['ipbanned']['expiration'] < TIMESTAMP) {
			require_once libfile('function/cache');
			updatecache('ipbanned');
		}
		return preg_match("/^(".$_G['cache']['ipbanned']['regexp'].")$/", $onlineip);
	}
}

function checkformulaperm($formula) {
	$formula = preg_replace('/(\{([\d\.\-]+?)\})/', "'\\1'", $formula);
	return checkformulasyntax(
		$formula,
		array('+', '-', '*', '/', '(', ')', '<', '=', '>', '!', 'and', 'or', ' ', '{', '}', "'"),
		array('regdate', 'regday', 'regip', 'lastip', 'buyercredit', 'sellercredit', 'digestposts', 'posts', 'threads', 'oltime', 'extcredits[1-8]', 'field[\d]+')
	);
}

function debug($var = null) {
	echo '<pre>';
	if($var === null) {
		print_r($GLOBALS);
	} elseif($var == 'trace') {
		$db = & DB::object();
		print_r($db->sqldebug);
	} else {
		print_r($var);
	}
	exit();
}

function debuginfo() {
	global $_G;
	if(DEBUG) {
		$db = & DB::object();
		$sqlinfo = $db->sqldebug;
		if(!is_array($sqlinfo)){
			$sqlinfo = array();
		}
		$i = 1;
		foreach($sqlinfo as $k => $v){
			$info .= $i.':'.$v[1].'s:'.$v[0].'
';
			$i += 1;
		}
		$_G['debuginfo'] = array('time' => number_format((microtime(true) - $_G['starttime']), 6), 'queries' => $db->querynum, 'memory' => ucwords($_G['memory']), 'sqlinfo' => $info);
		return TRUE;
		//return $debuginfo;
	} else {
		return FALSE;
	}
}

function showmessage($message, $url = '', $login = false, $refreshspan = 2, $values = array(), $extraparam = array(), $custom = 0) {
	global $_G, $show_message, $url_forward, $allowreturn, $param, $refreshtime;

	$param = array(
		'header'	=> false,
		'timeout'	=> null,
		'refreshtime'	=> null,
		'locationtime'	=> true,
		'alert'		=> null,
		'return'	=> false,
		'redirectmsg'	=> 0,
		'msgtype'	=> 1,
		'showmsg'	=> true,
		'showdialog'	=> false,
		'login'		=> $login,
		'handle'	=> false,
		'extrajs'	=> '',
	);
	//标题
	$GLOBALS['title'] = lang('message', 'title_board_message');

	define('CACHE_FORBIDDEN', TRUE);
	$leftmsg = '';

	//如果存在跳转地址，timeout为真
	if($url)
		$param['timeout'] = true;

	foreach($extraparam as $k => $v) {
		$param[$k] = $v;
	}
	//这里给refreshtime赋值为自动刷新时间，其中 $timedefault的值
	$timedefault = intval($param['refreshtime'] === null ? $refreshspan : $param['refreshtime']);
	if($param['timeout'] !== null) {
		$refreshsecond = !empty($timedefault) ? $timedefault : 3;
		$refreshtime = $refreshsecond * 1000;
	} else {
		$refreshtime = $refreshsecond = 0;
	}
	//如果要求直接跳转到登陆页面的话，如下情况为假
	if($param['login'] && $_G['uid'] || $url) {
		$param['login'] = false;
	}

	$param['header'] = $url && $param['header'] ? true : false;
	//这里没提示消息，直接跳转
	if($param['header']) {
		header("HTTP/1.1 301 Moved Permanently");
		dheader("location: ".str_replace('&amp;', '&', $url));
	}
	//这里对信息进行处理
	$show_message = lang('message', $message, $values);
	//exit($show_message);
	$show_jsmessage = str_replace("'", "\\\'", strip_tags($show_message));
	$extra = '';
	//exit($extra.$url);
	if(!$param['showmsg']) {
		$show_message = '';
	}
	//控制返回上一页
	$allowreturn = !$param['timeout'] && stristr($show_message, lang('message', 'return')) || $param['return'] ? true : false;
	//控制多少秒后页面跳转
	if($param['locationtime'] !== null) {
		$param['locationtime'] = $param['locationtime'] === true ? $timedefault : $param['locationtime'];
		$leftmsg = '<br />'.$param['locationtime'].lang('message', 'showmessage_locationtime');
	}
	//如果不存在extra
	if(!$extra && $param['timeout']) {
		$extra .= 'setTimeout("window.location.href =\''.$url.'\';", '.$refreshtime.');';
	}
	//exit($leftmsg.$extra.$st.$show_message);
	$show_message .= $extra ? '<script type="text/javascript" reload="1">'.$extra.'</script>'.$leftmsg : '';
	$show_message .= $param['extrajs'] ? $param['extrajs'] : '';
	$url_forward = $url;
	//exit($show_message);

	include template('common/showmessage');
	dexit();
}

function dexit($message = '') {
	echo $message;
	//output();
	exit();
}

function dheader($string, $replace = true, $http_response_code = 0) {
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if(empty($http_response_code)) {
		@header($string, $replace);
	} else {
		@header($string, $replace, $http_response_code);
	}
	if(preg_match('/^\s*location:/is', $string)) {
		exit();
	}
}

function sendmail($to, $email_subject, $email_message, $from = 'admin@favlab.com (科学实验室)'){//$to可以是数组或者单个或者用,分开的
	$charset = CHARSET;
	$email_subject = htmlspecialchars($email_subject);
	$email_message = $email_message;
	$maildelimiter = "\r\n" ;//: ($mail['maildelimiter'] == 2 ? "\r" : "\n");
	$headers = "From: $from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: science lab {$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/plain; charset= $charset{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}Message-ID: <".gmdate('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";

	$email_subject = '=?'.$charset.'?B?'.base64_encode(str_replace("\r", '', str_replace("\n", '', $email_subject))).'?=';
	$email_message = chunk_split(base64_encode(str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $email_message)))))));
	
	if(is_array($to)){
		foreach($to as $t){
			if(!@mail($t, $email_subject, $email_message, $headers))
				return 0;
		}
	}else{
		if(preg_match("/([\w\-\.]+@[\w\-\.]+(\.\w+)+,)+/", $to)){
			$toarr = explode(',', $to);
			foreach($toarr as $t){
				if(!@mail($t, $email_subject, $email_message, $headers))
					return 0;
			}
			//sendmail($toarr, $email_subject, $email_message, $from);
		}else{
			$to = trim($to);
			if(!@mail($to, $email_subject, $email_message, $headers))
				return 0;
		}
	}
	return 1;
}

function is_utf8($word){
	if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$word) == true)
		return true;
	else
		return false;
}

function uni_decode($s) {
	preg_match_all('/\&\#([0-9]{5})\;/', $s, $html_uni);
	preg_match_all('/\\\u([0-9a-f]{4})/ie', $s, $js_uni);
	$source = array_merge($html_uni[0], $js_uni[0]);
	$js = array();
	for($i=0;$i<count($js_uni[1]);$i++) {
		$js[] = hexdec($js_uni[1][$i]);
	}
	$utf8 = array_merge($html_uni[1], $js);
	$code = $s;
	for($j=0;$j<count($utf8);$j++) {
		$code = str_replace($source[$j], unicode2utf8($utf8[$j]), $code);
	}
	return $code;
}

function diconv($in, $charset, $tocharset = 'UTF8') {
	include_once libfile('class/chinese');
	if(strtolower($charset) == 'unicode') {
		if(strtolower($tocharset) == 'utf-8') {
			return uni_decode($in);
		} elseif(strtolower($tocharset) == 'gbk') {
			$in = uni_decode($in);
			$ch = new Chinese('utf-8', 'gbk', $in);
			$out = $ch->ConvertIT();
			return $out;
		}
	} else {
		$ch = new Chinese($charset, $tocharset, $in);
		$out = $ch->ConvertIT();
		return $out;
	}
}

function cutstr($string, $length, $dot = ' ...') {
	if(strlen($string) <= $length) {
		return $string;
	}

	$pre = '{%';
	$end = '%}';
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);

	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8') {

		$n = $tn = $noc = 0;
		while($n < strlen($string)) {

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}

			if($noc >= $length) {
				break;
			}

		}
		if($noc > $length) {
			$n -= $tn;
		}

		$strcut = substr($string, 0, $n);

	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut.$dot;
}
?>